<template>
  <div class="wrap">
    <a-drawer :title="title" placement="right" :closable="true" :visible="visible"
      :headerStyle="{ 'padding-top': '20px' }" width="495px" :after-visible-change="afterVisibleChange" zIndex="2"
      @close="onClose">
      <div id="components-form-demo-vuex">
        <a-form-model ref="ruleForm" :model="form" :rules="rules" layout="vertical"> <a-form-model-item ref="department"
            label="组织代码" prop="id">
            <a-input v-model="form.id" placeholder="请输入组织代码" />
          </a-form-model-item>
          <a-form-model-item ref="department" label="部门名称" prop="department">
            <a-input v-model="form.department" placeholder="请输入部门名称" />
          </a-form-model-item>
          <a-form-model-item label="部门" prop="parentDepartmentName">
            <a-input v-model="form.parentDepartmentName" readOnly placeholder="点击选择部门" @click="showModal" />
          </a-form-model-item>
          <a-form-model-item label="类型">
            <a-select
            default-value="1"
              style="width: 120px"
              v-model="deptType"
            >
              <a-select-option value="1"> 实体部门 </a-select-option>
              <a-select-option value="0"> 虚拟部门</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="分类">
            <a-select
             v-model="form.type"
             :default-value="form.type"
              style="width: 120px"
              readonly
            >
              <a-select-option @change="typeChange" v-for="(item,index)  in typeInfo" :key="index" :value="item.dictCode+''"  :label="item.dictLabel"> {{item.dictLabel}} </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="状态">
            <a-select v-model="form.status" :default-value="form.status" style="width: 120px">
              <a-select-option :value="1"> 启用 </a-select-option>
              <a-select-option :value="0"> 禁用</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click="onSubmit"> 确 定 </a-button>
            <a-button style="margin-left: 10px" @click="resetForm" v-show="addOrUpdate == 0">
              重 置
            </a-button>
          </a-form-model-item>
        </a-form-model>
        <div>
          <a-modal v-model="modelVisible" title="部门列表" on-ok="handleOk" @cancel="noMoelSelect">
            <template slot="footer">
              <a-button key="back" @click="handleCancel"> 取消 </a-button>
              <a-button key="submit" type="primary" :loading="loading" @click="handleOk">
                确定
              </a-button>
            </template>
            <a-tree style="
                min-width: 170px !important;
                margin-top: 10px;
                max-height: 400px;
                overflow-y: auto;
              " :tree-data="nodeData" :autoExpandParent="true" :defaultExpandParent="true"
              :replace-fields="replaceFields" :defaultExpandedKeys="[nodeData[0].id]" show-icon @select="selectDept">
            </a-tree>
          </a-modal>
        </div>
      </div>
    </a-drawer>
    <a-row style="background: #fff; border-radius: 6px">
      <a-col :span="6" style="overflow-y: auto">
        <!-- <a-tree
          style="
            min-width: 170px !important;
            margin: 10px;
            height: calc(100vh - 250px);
          "
          :tree-data="nodeData"
          :autoExpandParent="true"
          :defaultExpandParent="true"
          defaultExpandAll
          :defaultExpandedKeys="[nodeData[0].id]"
          show-icon
          @select="onSelect"
        >
          <template #title="{ orgname, id }">
            <a-dropdown :trigger="['contextmenu']">
              <span>{{ orgname }}</span>
              <template #overlay>
                <a-menu
                  @click="({ key: menuKey }) => onContextMenuClick(id, menuKey)"
                >
                  <a-menu-item key="1">编辑</a-menu-item>
                  <a-menu-item key="2">删除</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </a-tree> -->

        <el-input placeholder="请输入搜索的关键字" style="width: 250px;margin: 14px 0 0 20px;" clearable size="medium"
          v-model="filterText"></el-input>
        <el-tree style="margin: 6px 0 0 10px;height: calc(100vh - 260px);overflow: scroll;" :default-expanded-keys="['1']"
          node-key="id" highlight-current :filter-node-method="filterNode" :data="nodeData" :props="defaultProps1"
          accordion @node-click="onSelect" ref="tree">
        </el-tree>
      </a-col>

      <a-col :span="18" style="
          padding: 10px;
          border-left: 4px solid #edeff2;
          height: calc(100vh - 198px);
        ">
        <div style="margin-top: 10px">
          <div>
            <span style="color: #171a1d; font-weight: 600; font-size: 17px">{{ deptName ? deptName : '崇明教育' }}</span>
          </div>
          <div style="margin-top: 15px;width: min-width: 100%;" class="set_font_set">
            <a-button type="primary" @click="addDept" v-if="isAdmin">
              <a-icon type="user-add" />添加部门
            </a-button>
            <a-input placeholder="请输入组织名称" style="width: 250px; margin-left: 20px" v-model="deptSelectName"
              allow-clear></a-input>
            <a-select default-value="1" style="width: 200px; padding-left: 20px" @change="handleChangeDpet">
              <a-select-option value="1"> 实体部门 </a-select-option>
              <a-select-option value="0"> 虚拟部门</a-select-option>
            </a-select>
            <a-select default-value="1" style="width: 200px; padding-left: 20px" @change="handleChangeDpetStatus">
              <a-select-option value="1"> 启用 </a-select-option>
              <a-select-option value="0"> 禁用</a-select-option>
            </a-select>
            <a-button type="primary" @click="searchDept" style="margin-left: 20px">
              <a-icon type="search" />搜 索
            </a-button>
          </div>
        </div>
        <a-table rowKey="id" style="margin-top: 15px" :columns="columns"  :scroll="{ y: tableHeight }" :data-source="userInfo" bordered>
          <span slot="status" slot-scope="status">
            <span v-if="status == 1">启用</span>
            <span v-if="status == 0">禁用</span>
          </span>

          <span slot="cz" slot-scope="cz, record">
            <a-button type="link" style="padding-left:20px;" @click="editDept(record)" v-if="isAdmin">修改部门</a-button>
            <a-button type="link" style="padding-left:20px;" @click="showDeleteConfirm(record)" v-if="isAdmin">删除部门</a-button>
            <!-- <a style="padding-left:20px;" @click="editDept(record)">修改部门</a> -->
            <!-- <a @click="showDeleteConfirm(record)" style="padding-left:20px;">删除部门</a> -->
          </span>
        </a-table>

        <!-- <el-table :data="userInfo" stripe :height="tableHeight" border style="width: 100%;margin-top: 15px">
          <el-table-column prop="orgName" label="组织名称"></el-table-column>
          <el-table-column prop="parentName" label="父组织"> </el-table-column>
          <el-table-column prop="status" label="组织状态" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.status == 1">启用</span>
              <span v-if="scope.row.status == 0">禁用</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button @click.native.prevent="editDept(scope.$index, scope)" type="text" size="small">修改部门</el-button>
              <el-button @click.native.prevent="showDeleteConfirm(scope.$index, scope)" type="text"
                size="small">删除部门</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination background style="text-align: right;margin-top: 10px;" :current-page="paginationPage.page"
          :page-sizes="[10, 20, 30, 50, 100, 300]" :page-size="paginationPage.size" :total="paginationPage.totalData"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination> -->
      </a-col>
    </a-row>
  </div>
</template>

<script>
const columns = [
  {
    title: "组织名称",
    dataIndex: "orgName",
    scopedSlots: { customRender: "name" },
  },
  {
    title: "父组织",
    dataIndex: "parentName",
    scopedSlots: { customRender: "age" },
  },
  {
    title: "组织状态",
    dataIndex: "status",
    scopedSlots: { customRender: "status" },
    width: 100,
  },
  {
    title: "操作",
    dataIndex: "cz",
    scopedSlots: { customRender: "cz" },
  },
];const data = [];
for (let i = 0; i < 100; i++) {
  data.push({
    key: i.toString(),
    name: `Edrward ${i}`,
    age: 32,
    address: `London Park no. ${i}`,
  });
}

// 数组对象中查找符合目标的对象
const parseArray = function (objArray, key, value) {
  for (let i in objArray) {
    let element = objArray[i];
    if (typeof element === "object") {
      let result = parseArray(element, key, value);
      if (result) return result;
    } else {
      if (i === key) {
        if (element === value) return objArray;
      }
    }
  }
};

import contacts from "@/api/organizations";
export default {
  name: "index1",
  data() {
    this.cacheData = data.map((item) => ({ ...item }));
    return {
      selectedTreeID: '',//当前选中的树节点id
      paginationPage: {
        page: 1,
        size: 10,
        totalData: 0
      },
      filterText: '',
      defaultProps1: {
        children: 'children',
        label: 'orgname'
      },
      form: {
        parentDepartmentId: "",
        parentDepartmentName: "",
        department: "",
        status: "",
        type: "2",
        id: ""
      },
      data,
      columns,
      editingKey: "",
      deptName: "",
      userInfo: [],
      visible: false,
      addOrUpdate: 0,
      modelVisible: false,
      getById: "",
      deptStatus: 1,
      deptType: '1',
      roleId: "",
      typeInfo: [],
      
      isAdmin: false,
      deptSelectName: "",
      replaceFields: {
        title: "orgname",
        key: "id",
        child: "children",
      },
      rules: {
        id: [
          { required: true, message: "组织代码不能为空", trigger: "blur" },
        ],
        department: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
        ],
        parentDepartmentName: [
          { required: true, message: "上级部门不能为空", trigger: "change" },
        ],
      },
      nodeData: [{}],
      deptId: "",
      codeLine: "",
      selectedKeys: null,
      filterResource: null,
    };
  },
  async created() {
    // 树的获取
    this.getInit();

    // this.treeOnLoad = false;
  },

  watch: {
    filterText(val) { //监听树节点搜索
      this.$refs.tree.filter(val);
    },
  },

  mounted() {
    // this.GetLimsConfigNode();
    // this.getAllDept();
    this.getRole();
    this.getChildren(["1"]); //初始化表格
  },
  computed: {
    tableHeight() {
      return window.innerHeight - 430 + "px";
    },
  },
  methods: {

    //TODO 分页
    handleSizeChange(val) {
      //每页多少条
      this.paginationPage.size = val;
      this.getChildren(this.selectedTreeID)
    },
    handleCurrentChange(val) {
      //当前页
      this.paginationPage.page = val;
      this.getChildren(this.selectedTreeID)
    },

    filterNode(value, data) { //树节点搜索
      if (!value) return true;
      return data.orgname.indexOf(value) !== -1;
    },
    typeChange(val) {
      this.form.type = val
    },
    // handleChangeStatus(val) {
    //   this.form.status = val;
    // },
    async getTypeInfo() {
      await contacts.getDictionariesInfo().then((res) => {
        this.typeInfo = res.data.data.dictionaries
      })
    },
    searchDept() {
      if (this.getById == "" || this.getById == null) {
        this.$message({
          type: "error",
          message: "请选择部门",
        });
      } else {
        let data = {
          orgId: this.getById,
          name: this.deptSelectName,
          status: this.deptStatus,
          enable: this.deptType,
        };
        contacts.getConditionChildrenInfo(data).then((res) => {
          this.userInfo = res.data;
        });
      }
    },

    handleChangeDpet(val) {
      this.deptType = val;
    },
    handleChangeDpetStatus(val) {
      this.deptStatus = val;
    },
    onContextMenuClick(treeKey, menuKey) {
      switch (menuKey) {
        case "1": //编辑
          this.addOrUpdate = 1;
          this.getDeptDetails(treeKey);
          break;
        case "2": //删除
          this.showDeleteConfirm(treeKey);
          break;
      }
    },
    getDeptDetails(val) {
      contacts.getDeptInfo(val).then((res) => {
        this.editDept(res.data.data.organizations);
      });
    },
    showDeleteConfirm(obj) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          contacts.delOrg(obj.id).then((res) => {
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getInit();
              this.getChildren(obj.parentId);
            }else if(res.data.code == 400){
              this.$message({
                type: "error",
                message: res.data.msg,
              });
              this.getInit();
              this.getChildren(obj.parentId);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    getRole() {
      contacts.getRoleByUser().then((res) => {
        for (let i = 0; i < res.data.data.deptCodeRole.length; i++) {
          if (res.data.data.deptCodeRole[i].code == "t001") {
            this.isAdmin = true;
          }
        }
      });
    },
    editDept(obj) {
      this.getTypeInfo()
      var that = this;
      //  setTimeout(res=>{
      //   console.log("2222")
      //   that.form.type=obj.orgtype;
      //  },1000)

      this.addOrUpdate = 1;
      (this.deptId = obj.id),
        this.form.type = obj.orgtype;
      (this.form.status = obj.status),
        (this.form.department = obj.orgName),
        (this.deptType = obj.enable),
        (this.form.parentDepartmentId = obj.parentId),
        (this.form.parentDepartmentName = obj.parentName);
      this.visible = true;
    },
    resetForm() {
      (this.form = {
        parentDepartmentId: "",
        parentDepartmentName: "",
        department: "",
      }),
        this.$refs.ruleForm.resetFields();
    },
    selectDept(params, e) {
      this.form.parentDepartmentName = e.node._props.title;
      this.form.parentDepartmentId = params[0];
    },
    async getInit() {
      let res = await contacts.getNodeData(); // 获取树节点信息的函数
      this.deptName = res.data.orgname;
      let arr = res.data;
      this.nodeData = arr;
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let organization = {
            parentId: this.form.parentDepartmentId,
            parentName: this.form.parentDepartmentName,
            orgName: this.form.department,
            id: this.form.id,
            enable: this.deptType,
            status: this.form.status,
            orgtype: this.form.type
          };
          if (this.addOrUpdate == 0) {
            contacts.addOrg(organization).then((res) => {
              if (res.data.code == 200) {
                this.$message.success("添加成功");
                this.getInit();
                this.getChildren(this.getById);
                this.onClose();
              }
            });
          }
          if (this.addOrUpdate == 1) {
            organization.id = this.deptId;
            contacts.updateOrg(organization).then((res) => {
              if (res.data.code == 200) {
                this.$message.success("修改成功");
                this.getInit();
                this.getChildren(this.getById);
                this.onClose();
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    handleOk() {
      this.modelVisible = false;
    },
    noMoelSelect() {
      this.form.parentDepartmentName = "";
      this.form.parentDepartmentId = "";
    },
    handleCancel(e) {
      this.form.parentDepartmentName = "";
      this.form.parentDepartmentId = "";
      this.modelVisible = false;
    },
    onClose() {
      this.form = {
        parentDepartmentId: "",
        parentDepartmentName: "",
        department: "",
        status: "",
      };
      this.addOrUpdate = 0;
      (this.deptId = ""), (this.visible = false);
    },
    showModal() {
      this.modelVisible = true;
    },
    showDrawer() {
      this.getTypeInfo();
      this.visible = true;


    },
    addDept() {
      this.form.status = 1

      this.title = "添加子部门";
      this.showDrawer();
    },
    // 获取全部节点树
    async GetLimsConfigNode() {
      // this.nodeData = await GetLimsConfigNodeData();
    },
    // 新增、修改节点操作，此处为打开新增修改界面，调用实际后端接口进行节点的处理操作
    async nodeHandle() { },
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.find((item) => key === item.key);
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },
    edit(key) {
      const newData = [...this.data];
      const target = newData.find((item) => key === item.key);
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.data = newData;
      }
    },
    save(key) {
      const newData = [...this.data];
      const newCacheData = [...this.cacheData];
      const target = newData.find((item) => key === item.key);
      const targetCache = newCacheData.find((item) => key === item.key);
      if (target && targetCache) {
        delete target.editable;
        this.data = newData;
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      this.editingKey = "";
    },
    cancel(key) {
      const newData = [...this.data];
      const target = newData.find((item) => key === item.key);
      this.editingKey = "";
      if (target) {
        Object.assign(
          target,
          this.cacheData.find((item) => key === item.key)
        );
        delete target.editable;
        this.data = newData;
      }
    },
    getChildren(params) {
      contacts.getChildrenInfo(params).then((res) => {
        this.paginationPage.totalData = res.data.length
        this.userInfo = res.data;
      });
    },
    async onSelect(params, e) {
      this.deptName = params.orgname;
      this.getById = params.id;
      this.selectedTreeID = params.id;
      this.getChildren(this.getById);
    },
  },
};
</script>

<style lang="less" scoped>
.wrap {
  position: relative;
}

.set_button_margin_left {
  margin-left: 15px;
}
</style>

<style lang="less" >
.set_font_size {
  font-size: 14px !important;
}
</style>
<style lang="less">
.ant-drawer-title {
  margin: 0;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  font-size: 14px;
  line-height: 22px;
}

.set_drawer_div {
  margin-top: -15px;
  width: 490px;
  height: 48px;
  font-weight: 500;
  color: #171a1d;
  font-size: 14px;
}
</style>

